import yaml
import numpy as np
import importlib
import time, math

from .file_io import read_excel
from .file_io import global_output
from .target_list import target_list
from .satellite_formation import basic_sate_form
from . import planner 

class science_operations(object):

    def __init__(self, yaml_file_path = ""):
        yaml_str = ''
        with open(yaml_file_path, mode='r', encoding='utf-8') as yaml_file:
            yaml_str = yaml_file.read()
            yaml_config = yaml.load(yaml_str, Loader=yaml.FullLoader)

        # 动态参量，需在yml中给定
        #self.__min_time = yaml_config.get("MinTime", 5.)                    # 优化的目标时间T_target day
        self.__operation_method = yaml_config.get("OperationMethod", "benchmark_planner")    # 选择使用的规划方法，命名需按planner目录下的module命名
        self.__operation_config = yaml_config.get("OperationParams", {})    # 选择使用的规划方法，命名需按planner目录下的module命名
        self.__output_config = yaml_config.get("OutputConfig", {})    # 输出文件控制参数
        self.__rd_excel = read_excel(yaml_config["Targets"])
        self.__random_seed = 0

        # 指定优化方法
        operations_mod = importlib.import_module(f".planner.{self.__operation_method}", package="miyinff")
        operation_clz = getattr(operations_mod, self.__operation_method)
        self.__operation_obj = operation_clz(self.__operation_config)

        # 初始化输出
        global_output.initial(self.__output_config, self.__operation_method)
        global_output.write_log("Yaml Config:\n")
        global_output.write_log(yaml_str)

    def initialize(self):
        # 初始化卫星队列
        #formation_type = self.__operation_obj.sate_form_type()
        #sate_form_mod = importlib.import_module(f".satellite_formation.{formation_type}", package="miyinff")
        #sate_form_clz = getattr(sate_form_mod, formation_type)
        #self.__sate_form = sate_form_clz(self.__formation_status)

        # 设置随机数
        t_now = time.time()
        self.__random_seed = int((t_now-math.floor(t_now))*1e9)
        np.random.seed(self.__random_seed)
        global_output.write_log(f"Random seed: {self.__random_seed}")

        # 读取星表
        self.__tg_list = target_list(self.__rd_excel.pdarray(), self.__operation_obj)

    def operation(self):
        self.__operation_obj.initialize(self.__tg_list, random_seed=self.__random_seed) 
        self.__operation_obj.operation()

        global_output.save_log()

    '''
    @staticmethod
    def output_path():
        return global_output.output_path

    @staticmethod
    def output_name():
        return global_output.output_name

    @staticmethod
    def write_log_file(log):
        global_output.write_log(log)

    '''